package com.bestcem.xm.survey.grpc.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.deliver.grpc.v1.services.*;
import com.bestcem.xm.survey.convert.grpc.SurveyGrpcConvertMapper;
import com.bestcem.xm.survey.grpc.client.dto.CustomLinkDeliverDto;
import com.bestcem.xm.survey.grpc.client.dto.DeliverDto;
import com.bestcem.xm.survey.grpc.client.dto.DeliverExtParamsDto;
import com.bestcem.xm.survey.grpc.client.dto.DeliverWechatmpRecordDto;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class DeliverGrpcClient {

    @GrpcClient(GrpcClientNames.DS_DELIVER)
    private BpDeliverServiceGrpc.BpDeliverServiceBlockingStub stub;

    @GrpcClient(GrpcClientNames.DS_DELIVER)
    private BaseDeliverServiceGrpc.BaseDeliverServiceBlockingStub baseStub;

    private final SurveyGrpcConvertMapper grpcConvertMapper;

    public DeliverGrpcClient(SurveyGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    public Integer getVersionBySurveyId(String surveyId) {
        GetVersionBySurveyIdRequest.Builder builder = GetVersionBySurveyIdRequest.newBuilder();
        builder.setSurveyId(surveyId);

        try {
            GetVersionBySurveyIdResponse response = baseStub.getVersionBySurveyId(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] deliver getVersionBySurveyId error {}", response);
            }
            return response.getVersion();
        } catch (Exception e) {
            log.error("[survey] ex deliver getVersionBySurveyId  ErrorMsg: {}", e.getMessage());
            return null;
        }
    }

    public List<DeliverExtParamsDto> listDeliverExtparams(JSONObject params) {
        ListDeliverExtparamsRequest.Builder builder = ListDeliverExtparamsRequest.newBuilder();
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        params.remove("search");

        String statusStr = params.getString("status");
        if (StrUtil.isNotEmpty(statusStr) && JSONUtil.isTypeJSONArray(statusStr)) {
            builder.addAllStatus(JSONArray.parseArray(statusStr).toJavaList(Integer.class));
            params.remove("status");
        } else {
            builder.addAllStatus(Lists.newArrayList());
        }

        DeliverExtParamsDto requestDto = JSONObject.toJavaObject(params, DeliverExtParamsDto.class);
        builder.setDeliverExtparams(grpcConvertMapper.toGrpcDeliverExtparams(requestDto));

//        builder.addAllFields(null);
        try {
            DeliverExtparamsSearchResponse response = baseStub.listDeliverExtparams(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] listDeliverExtparams Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toDeliverExtParamsDtoList(response.getDeliverExtparamsListList());
        } catch (Exception e) {
            log.error("[survey] ex listDeliverExtparams Error, ErrorMsg:", e);
            return null;
        }
    }

    public JSONObject getQrDeliverDisable(String deliverId, String code) {
        GetQrDeliverDisableRequest.Builder builder = GetQrDeliverDisableRequest.newBuilder();
        builder.setDeliverId(deliverId);
        if (!StrUtil.isEmptyIfStr(code)) {
            builder.setCode(code);
        }

        try {
            GetQrDeliverDisableResponse response = stub.getQrDeliverDisable(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getQrDeliverDisable Error, ErrorMsg: {}", response);
                return new JSONObject();
            }

            JSONObject result = new JSONObject();
            result.put("disable", response.getResultObj().getDisable());
            result.put("status", response.getResultObj().getStatus());
            return result;
        } catch (Exception e) {
            log.error("[survey] ex getQrDeliverDisable Error, ErrorMsg:", e);
            return new JSONObject();
        }
    }

    public JSONObject getDedicatedDeliverDel(String deliverId, String dedCode) {
        GetDedicatedDeliverDelRequest.Builder builder = GetDedicatedDeliverDelRequest.newBuilder();
        builder.setDeliverId(deliverId);
        builder.setDedCode(dedCode);

        try {
            GetDedicatedDeliverDelResponse response = stub.getDedicatedDeliverDel(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getDedicatedDeliverDel Error, ErrorMsg: {}", response);
                return new JSONObject();
            }

            JSONObject result = new JSONObject();
            result.put("is_deleted", response.getIsDeleted());
            return result;
        } catch (Exception e) {
            log.error("[survey] ex getDedicatedDeliverDel Error, ErrorMsg:", e);
            return new JSONObject();
        }
    }

    public List<CustomLinkDeliverDto> listCustomLinkDeliver(JSONObject params) {
        log.error("[survey] deliverclient listCustomLinkDeliver params={}", params.toJSONString());
        //deliver_id survey_id param_only_aging_type 3个参数
        ListCustomLinkDeliverRequest.Builder builder = ListCustomLinkDeliverRequest.newBuilder();
        builder.setSearch(Optional.ofNullable(params.getString("search")).orElse(""));
        params.remove("search");

        String statusStr = params.getString("status");
        if (StrUtil.isNotEmpty(statusStr) && JSONUtil.isTypeJSONArray(statusStr)) {
            builder.addAllStatus(JSONArray.parseArray(statusStr).toJavaList(Integer.class));
            params.remove("status");
        } else {
            builder.addAllStatus(Lists.newArrayList());
        }

        CustomLinkDeliverDto requestDto = JSONObject.toJavaObject(params, CustomLinkDeliverDto.class);
        builder.setCustomLinkDeliver(grpcConvertMapper.toGrpcCustomLinkDeliver(requestDto));

//        builder.addAllFields(null);
        try {
            CustomLinkDeliverSearchResponse response = baseStub.listCustomLinkDeliver(builder.buildPartial());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] listCustomLinkDeliver Error, ErrorMsg: {}", response);
                return Lists.newArrayList();
            }
            return grpcConvertMapper.toCustomLinkDeliverDtoList(response.getCustomLinkDeliverListList());
        } catch (Exception e) {
            log.error("[survey] ex listCustomLinkDeliver Error, ErrorMsg:", e);
            return Lists.newArrayList();
        }
    }

    public DeliverDto getDeliver(String deliverId) {
        if (StrUtil.isBlankIfStr(deliverId)) {
            log.error("getDeliver error:deliverId is null");
            return null;
        }
        GetDeliverRequest.Builder builder = GetDeliverRequest.newBuilder();
        builder.setId(deliverId);
        try {
            DeliverResponse response = baseStub.getDeliver(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getDeliver Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toDeliverDto(response.getDeliver());
        } catch (Exception e) {
            return null;
        }
    }

    public DeliverWechatmpRecordDto getWechatmprecord(String deliverId) {
        GetWechatMPRecordRequest.Builder builder = GetWechatMPRecordRequest.newBuilder();
        builder.setId(deliverId);
        try {
            WechatMPRecordResponse response = baseStub.getWechatMPRecord(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getWechatMPRecord Error, ErrorMsg: {}", response);
                return null;
            }
            return grpcConvertMapper.toDeliverWechatmpRecordDto(response.getWechatMPRecord());
        } catch (Exception e) {
            log.error("[survey] ex getWechatMPRecord Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<String> getDeliverIdsByDtPid(String deliver_dt_gte, String deliver_dt_lt, String project_id) {
        GetDeliverIdsByDtPidRequest.Builder builder = GetDeliverIdsByDtPidRequest.newBuilder();
        builder.setDeliverDtGte(deliver_dt_gte);
        builder.setDeliverDtLt(deliver_dt_lt);
        builder.setProjectId(project_id);
        try {
            GetDeliverIdsByDtPidResponse response = baseStub.getDeliverIdsByDtPid(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getDeliverIdsByDtPid Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getDeliverIdListList();
        } catch (Exception e) {
            log.error("[survey] ex getDedicatedDeliverDel Error, ErrorMsg:", e);
            return null;
        }
    }

    public List<DeliverSurvey> getDeliverSurveyV2(List<String> memberIds) {
        GetDeliverSurveyV2Request.Builder builder = GetDeliverSurveyV2Request.newBuilder();
        builder.addAllMemberIds(memberIds);
        GetDeliverSurveyResponse response = baseStub.getDeliverSurveyV2(builder.build());
        if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
            log.error("[survey] getDeliverSurveyV2 Error, ErrorMsg: {}", response);
            return null;
        }
        return new ArrayList<>(response.getDeliverSurveyList());
    }
}
